<template>
  <Modal v-model="show" title="分配权限">
    <div style="height: 600px;overflow:hidden scroll;">
      <!--  VanTree中 提供了一个 getCheckedAndIndeterminateNodes 方法，用来获取勾选的所有节点   -->
      <VanTree ref="tree" :treeNodes="treeNodes" show-checkbox/>
    </div>
    <template #footer>
      <Button type="default" @click="show = false">关闭</Button>
      <Button :icon="treeBtn.icon" type="info" @click="treeNode">{{ treeBtn.text }}</Button>
      <Button type="primary" @click="savePermission">确定</Button>
    </template>
  </Modal>
</template>

<script>
import VanTree from "./VanTree.vue";

export default {
  props: {
    modelValue: {type: Boolean, required: true},
    roleId: {type: Number, required: true},
  },
  data() {
    return {
      treeBtnIndex: 0,
      treeBtnList: [
        {icon: 'md-add-circle', text: "全部选中"},
        {icon: 'ios-remove-circle', text: "全部取消"},
      ],
      checkStrictly: true,
      treeNodes: []
    }
  },
  created() {
     this.$api.queryPermissionTree(this.roleId).then(ret=> {
        if (ret.data.status) {
          this.treeNodes = ret.data.list ;
        }
     })
  },
  methods: {
    // 勾选获取取消所有
    selectOrCancelAllNodes(flag) {
      this.treeNodes.forEach(node => {
        this.selectOrCancelNode(node, flag);
      })
    },
    treeNode() {
      // 实现 全选 获取 取消
      this.selectOrCancelAllNodes(this.treeBtnIndex++ % 2 == 0);
    },

    selectOrCancelNode(node, flag) {
      node.checked = flag;
      if (node.children != null) {
        node.children.forEach(n => this.selectOrCancelNode(n, flag))
      }
    },
    checkedNodeAndParents(selectNodes, node) { // 实现 勾选子节点，自动勾选所有父节点
      console.log(selectNodes);
    },
    savePermission(){
       // 获取选中的所有节点
       let nodes = this.$refs.tree.getCheckedAndIndeterminateNodes();
       // 组装数据、调用接口、完成保存
       let nodeData = nodes.map(node => ({ id: node.id , level: node.level, tid: node.tid })) ;
       // 调用接口、完成 权限挂载
       this.$api.savePermission(this.roleId, nodeData).then(ret=> {
          if (ret.data.status) {
             this.$tips.success("权限分配成功") ;
             this.show = false ;
          }
       })
    }
  },
  components: {
    VanTree,
  },
  computed: {
    treeBtn() {
      return this.treeBtnList[this.treeBtnIndex % 2];
    },
    show: {
      get() {
        return this.modelValue ;
      },
      set(val) {
        this.$emit("update:model-value", val);
      }
    }
  }
}
</script>

<style>
</style>